//
//  AppDelegate.m
//  AOEProject
//
//  Created by techplus on 9/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#define XML_URL_VERSION (@"http://aoevietnamvideo.appspot.com/getvidnum")
#define XML_URL (@"http://aoevietnamvideo.appspot.com/aoevietnamvideo")
#define XML_HOTNEW_URL (@"http://aoevietnamvideo.appspot.com/gethotnew")
#define XML_HOtNEW_VERSION (@"http://aoevietnamvideo.appspot.com/getvidnum")

#import "AppDelegate.h"

#import "SummaryViewController.h"
#import "SplashViewController.h"
#import "AOE_XML_Parser.h"
#import "DetailViewController.h"
@implementation AppDelegate

@synthesize window = _window;
@synthesize tabBarController = _tabBarController;
@synthesize splashViewController = _splashViewController;
@synthesize response;

- (void)dealloc
{
    [_window release];
    [_tabBarController release];
    [_splashViewController release];
    [response release];
    [myVersion release];
    [webVersion release];
    [XMLconnection release];
    [verConn release];
    [response release];
    [paths release];
    [filePath release];
    [documentDirectory release];
    [filePath2 release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    // Override point for customization after application launch.
    ///CREATE SPLASH SCREEN
    self.splashViewController = [[[SplashViewController alloc]initWithNibName:@"SplashViewController" bundle:nil]autorelease];
    self.window.rootViewController = self.splashViewController;
//    [self.window addSubview:self.splashViewController.view];
    [self.window makeKeyAndVisible];
    self.splashViewController.lableProgress.text = @"Đang kiểm tra phiên bản ...";
    [self checkHotVersion];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
}
*/

#pragma marks - HANDLE CONNECTION
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    if (connection == XML_Hotnew_conn) {
        self.response = [[NSMutableData alloc]init];
        self.splashViewController.lableProgress.text = @"Bắt đầu tải dữ liệu...";
    }
    
    if(connection == XMLconnection){
        //totalResponse = [response expectedContentLength];
        self.response = [[NSMutableData alloc]init];
        self.splashViewController.lableProgress.text = @"Bắt đầu tải dữ liệu...";
    }
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data{
    if (connection == XML_Hotnew_conn) {
        totalReceived += [data length];
        float percent = (float)totalReceived/(float)1000000.0;
        
        int percent1 = percent*100.0;
        percent = (float)percent1/100.;
        //NSLog(@"received %d %f",totalReceived,percent);
        
        self.splashViewController.progressBar.progress = percent;
        self.splashViewController.lableProgress.text = [NSString stringWithFormat:@"Tải dữ liêụ ... %.2f MB",percent];
        [self.response appendData:data];
    }
    
    if(connection == XMLconnection)
    {
        totalReceived += [data length];
        float percent = (float)totalReceived/(float)1000000.0;
    
        int percent1 = percent*100.0;
        percent = (float)percent1/100.;
        //NSLog(@"received %d %f",totalReceived,percent);
    
        self.splashViewController.progressBar.progress = percent;
        self.splashViewController.lableProgress.text = [NSString stringWithFormat:@"Tải dữ liêụ ... %.2f MB",percent];
        [self.response appendData:data];
    }
    
}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection{
    
    if (connection == XML_Hotnew_conn) {
        NSLog(@"Get new xml complete ... saving...");
        self.splashViewController.lableProgress.text = [NSString stringWithFormat:@"Lưu dữ liệu ..."];
        [self savingHotnewData:self.response];
        NSLog(@"Saving complete loading resource...");
        self.splashViewController.lableProgress.text = @"Đang nạp giao diện ...";
        [self checkVersion];
        
    }
    
    if(connection == XMLconnection)
    {
        NSLog(@"Get new xml complete ... saving...");
        self.splashViewController.lableProgress.text = [NSString stringWithFormat:@"Lưu dữ liệu ..."];
        [self savingData:self.response];
        NSLog(@"Saving complete loading resource...");
        
        self.splashViewController.lableProgress.text = @"Đang nạp giao diện ...";
        [self loadResources];
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Alẻrt show...");
    [connection release];
    UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Lỗi kết nối" message:@"Bạn đang dùng phiên bản cũ" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
    [alert show];
}

#pragma marks - LOAD RESOURCE

-(void)loadResources{
    NSLog(@"Loading resourc...");
    //[[AOE_XML_Parser alloc]initSingleton];
    
    SummaryViewController *sumViewController = [[[SummaryViewController alloc] initWithNibName:@"SummaryViewController" bundle:nil] autorelease];
//    UINavigationController *sumNav = [[UINavigationController alloc] initWithRootViewController:sumViewController];
    UINavigationController *sumNav = [self customizedNavigationController];
    [sumNav setViewControllers:[NSArray arrayWithObject:sumViewController]];
    
    DetailViewController *hotViewController = [[DetailViewController alloc]initWithNibNameAndType:@"DetailViewController" bundle:nil:(NSInteger *)1:(NSInteger *)5:(NSInteger *)0:nil];
    hotViewController.title = @"Hot";
    hotViewController.tabBarItem.image = [UIImage imageNamed:@"hot.png"];
//    UINavigationController *hotNav = [[UINavigationController alloc]initWithRootViewController:hotViewController];
    UINavigationController *hotNav = [self customizedNavigationController];
    [hotNav setViewControllers:[NSArray arrayWithObject:hotViewController]];
    
    
    DetailViewController *newViewController = [[DetailViewController alloc]initWithNibNameAndType:@"DetailViewController" bundle:nil:(NSInteger *)1:(NSInteger *)4:(NSInteger *)0:nil];
    newViewController.title = @"New";
    newViewController.tabBarItem.image = [UIImage imageNamed:@"moi.png"];
//    UINavigationController *newtNav = [[UINavigationController alloc]initWithRootViewController:newViewController];
    UINavigationController *newtNav = [self customizedNavigationController];
    [newtNav setViewControllers:[NSArray arrayWithObject:newViewController]];
    
    self.tabBarController = [[[RXCustomTabBar alloc] init] autorelease];
    
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:newtNav, hotNav,sumNav, nil];
    
    self.splashViewController.lableProgress.text = @"Hoàn tất ...";
    
    self.tabBarController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    [self.splashViewController presentModalViewController:self.tabBarController animated:YES];

//    self.window.rootViewController = self.tabBarController;
//    [self.splashViewController release];
    
    [newtNav release];
    [hotNav release];
    [sumNav release];
    [hotViewController release];
    [newViewController release];
}

- (UINavigationController *)customizedNavigationController
{
    UINavigationController *navController = [[UINavigationController alloc] initWithNibName:nil bundle:nil];
    
    // Ensure the UINavigationBar is created so that it can be archived. If we do not access the
    // navigation bar then it will not be allocated, and thus, it will not be archived by the
    // NSKeyedArchvier.
    [navController navigationBar];
    
    // Archive the navigation controller.
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:navController forKey:@"root"];
    [archiver finishEncoding];
    [archiver release];
    [navController release];
    
    // Unarchive the navigation controller and ensure that our UINavigationBar subclass is used.
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    [unarchiver setClass:[SCNavigationBar class] forClassName:@"UINavigationBar"];
    UINavigationController *customizedNavController = [unarchiver decodeObjectForKey:@"root"];
    [unarchiver finishDecoding];
    [unarchiver release];
    
    // Modify the navigation bar to have a background image.
    SCNavigationBar *navBar = (SCNavigationBar *)[customizedNavController navigationBar];
    [navBar setTintColor:[UIColor brownColor]];
    [navBar setBackgroundImage:[UIImage imageNamed:@"navigator@portrait.png"] forBarMetrics:UIBarMetricsDefault];
    [navBar setBackgroundImage:[UIImage imageNamed:@"navigator@landscape.png"] forBarMetrics:UIBarMetricsLandscapePhone];
    
    return customizedNavController;
}

-(void)loadXML{
    
    totalReceived = 0;
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:XML_URL]];
    
    XMLconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if(XMLconnection)
    {
        self.splashViewController.lableProgress.text = @"Connection to server...";
    }
    else{
        self.splashViewController.lableProgress.text = @"Cant connect to server...";
    }
    
}

-(void)loadHotNewXML{
    totalReceived = 0;
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:XML_HOTNEW_URL]];
    
    XML_Hotnew_conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if(XML_Hotnew_conn)
    {
        self.splashViewController.lableProgress.text = @"Connection to server...";
    }
    else{
        self.splashViewController.lableProgress.text = @"Cant connect to server...";
    }

}

-(void)savingData:(NSMutableData *)data{
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentDirectory = [paths objectAtIndex:0];
    if(data)
    {
        filePath = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.xml"];
        NSString * xml_String = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [xml_String writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        NSLog(@"Overwrite version");
        filePath2 = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.version"];
        [webVersion writeToFile:filePath2 atomically:YES encoding:NSASCIIStringEncoding error:nil];
        [xml_String release];
    }
    
}

-(void)savingHotnewData:(NSMutableData *)data{
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentDirectory = [paths objectAtIndex:0];
    if(data)
    {
        filePath = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.hotnew.xml"];
        NSString * xml_String = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [xml_String writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        NSLog(@"Overwrite version");
        filePath2 = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.hotnew.version"];
        [webVersion writeToFile:filePath2 atomically:YES encoding:NSASCIIStringEncoding error:nil];
        [xml_String release];
    }

}

-(void)checkVersion{
    
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentDirectory = [paths objectAtIndex:0];
    filePath = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.version"];
    filePath2 = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.xml"];
    
    myVersion = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:nil];
    NSLog(@"myversion: %@",myVersion);
    
    //IF FIRST TIME RUN - GET ORIG VERSION FROM PROJECT
    if(myVersion == nil)
    {
        NSString *orginVersionPath = [[NSBundle mainBundle] pathForResource:@"data.version" ofType:nil];
        NSLog(@"%@",orginVersionPath);
        myVersion = [[NSString alloc]initWithContentsOfFile:orginVersionPath encoding:NSASCIIStringEncoding error:nil];
        NSLog(@"Orgin version: %@",myVersion);
        [myVersion writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil];
        NSLog(@"Write orgin version complete");
        //[orginVersionPath release];
    }
    
    //GET VERSION FROM INTERNET
    NSLog(@"Version checking...");
    NSURL *url = [NSURL URLWithString:XML_URL_VERSION];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    self.splashViewController.lableProgress.text = @"Kiểm tra phiên bản...";
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if (responseData) {
            webVersion = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
    }
    
    //[responseData release];
    //[request release];
    //[url release];
    
    if(webVersion == nil) //IF CAN'T GET VERSION FROM INTERNET
    {
        NSLog(@"Can't connect to get version");
        NSLog(@"Check xml data exist");
        
        //CHECKING HAVE XML DATA
        if([[NSFileManager defaultManager]fileExistsAtPath:filePath2])
        {
            NSLog(@"Data avaiable");
        }
        else{
            NSLog(@"Data not avaiable");
            NSLog(@"Get orgin data from project");
            
            NSString *orginXMLPath = [[NSBundle mainBundle] pathForResource:@"data.xml" ofType:nil];
            NSString *xml = [[NSString alloc]initWithContentsOfFile:orginXMLPath encoding:NSUTF8StringEncoding error:nil];
            [xml writeToFile:filePath2 atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
            NSLog(@"Write orgin xml complete");
            [xml release];
            //[orginXMLPath release];
            
        }
        [self loadResources];
        
    }
    else
    {
        //CHECKING WEBVERSION AND MYVERSION
        NSLog(@"webversion: %@",webVersion);
        if([webVersion isEqualToString:myVersion])
        {
            NSLog(@"Checking xml data exist");
            if([[NSFileManager defaultManager]fileExistsAtPath:filePath2])
            {
                NSLog(@"Data avaiable");
                NSLog(@"No need to update");
                [self loadResources];
            }
            else{
                NSLog(@"Data not avaiable");
                NSLog(@"Loading data from internet");
                [self loadXML];
            }
        }
        else
        {
            NSLog(@"Need to update data");
            NSLog(@"Load new XML");
            [self loadXML];
        }
    }
    
    
}
-(void)checkHotVersion{
    
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentDirectory = [paths objectAtIndex:0];
    filePath = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.hotnew.version"];
    filePath2 = [NSString stringWithFormat:@"%@%@",documentDirectory,@"data.hotnew.xml"];
    
    myVersion = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:nil];
    NSLog(@"myversion: %@",myVersion);
    
    //IF FIRST TIME RUN - GET ORIG VERSION FROM PROJECT
    if(myVersion == nil)
    {
        NSString *orginVersionPath = [[NSBundle mainBundle] pathForResource:@"data.hotnew.version" ofType:nil];
        NSLog(@"%@",orginVersionPath);
        myVersion = [[NSString alloc]initWithContentsOfFile:orginVersionPath encoding:NSASCIIStringEncoding error:nil];
        NSLog(@"Orgin version: %@",myVersion);
        [myVersion writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil];
        NSLog(@"Write orgin version complete");
        //[orginVersionPath release];
    }
    
    //GET VERSION FROM INTERNET
    NSLog(@"Version checking...");
    NSURL *url = [NSURL URLWithString:XML_HOtNEW_VERSION];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    
    self.splashViewController.lableProgress.text = @"Kiểm tra phiên bản...";
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if (responseData) {
        webVersion = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
    }
    
    //[responseData release];
    //[request release];
    //[url release];
    
    if(webVersion == nil) //IF CAN'T GET VERSION FROM INTERNET
    {
        NSLog(@"Can't connect to get hot new version");
        NSLog(@"Check xml data exist?");
        
        //CHECKING HAVE XML DATA
        if([[NSFileManager defaultManager]fileExistsAtPath:filePath2])
        {
            NSLog(@"Data avaiable");
        }
        else{
            NSLog(@"Data not avaiable");
            NSLog(@"Get orgin data from project");
            
            NSString *orginXMLPath = [[NSBundle mainBundle] pathForResource:@"data.hotnew.xml" ofType:nil];
            NSString *xml = [[NSString alloc]initWithContentsOfFile:orginXMLPath encoding:NSUTF8StringEncoding error:nil];
            [xml writeToFile:filePath2 atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
            NSLog(@"Write orgin xml complete");
            [xml release];
            //[orginXMLPath release];
            
        }
        [self checkVersion];
        
    }
    else
    {
        //CHECKING WEBVERSION AND MYVERSION
        NSLog(@"webversion: %@",webVersion);
        if([webVersion isEqualToString:myVersion])
        {
            NSLog(@"Checking xml data exist");
            if([[NSFileManager defaultManager]fileExistsAtPath:filePath2])
            {
                NSLog(@"Data avaiable");
                NSLog(@"No need to update");
                [self checkVersion];
            }
            else{
                NSLog(@"Data not avaiable");
                NSLog(@"Loading data from internet");
                [self loadHotNewXML];
            }
        }
        else
        {
            NSLog(@"Need to update data");
            NSLog(@"Load new XML");
            [self loadHotNewXML];
        }
    }
}
@end
